package QRCG;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieManager {

	// creating session cookies to be used by the forum application
	public static void addSessionCookies(HttpServletResponse response, String nickname,
			String password, String email) {

		// // generate the MD5 hash of the password to match the one in the
		// forum
		// // database
		// String hashPassword = Util.getMD5Hash(password);

		createCookie(response, "nickname", nickname, -1);
		createCookie(response, "password", password, -1);
		createCookie(response, "email", email, -1);

	}

	// removing session cookies by setting maxAge to 0
	public static void removeSessionCookies(HttpServletResponse response) {

		createCookie(response, "nickname", "", 0);
		createCookie(response, "password", "", 0);
		createCookie(response, "email", "", 0);
	}

	private static void createCookie(HttpServletResponse response, String key, String value,
			int maxAge) {

		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(maxAge);
		cookie.setPath("/");

		response.addCookie(cookie);
	}

	/**
	 * Searches for the session cookie with the given key, returns if there is
	 * any
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param key
	 *            key of the cookie
	 * @return the value of the cookie if there is any, null otherwise
	 */
	public static String getSessionCookieValue(HttpServletRequest request, String key) {
		Cookie[] cookieList = request.getCookies();
		if(cookieList == null){
			return null;
		}
		for (Cookie cookie : cookieList) {
			if(cookie.getName().equalsIgnoreCase(key) && cookie.getMaxAge() != 0){
				return cookie.getValue();
			}
		}
		return null;
	}

}
